from rest_framework import serializers
from .models import Order, OrderItem, Cart, OrderLog
from apps.flowers.serializers import FlowerListSerializer


class OrderItemSerializer(serializers.ModelSerializer):
    """订单商品序列化器"""
    
    class Meta:
        model = OrderItem
        fields = [
            'id', 'flower_name', 'flower_image', 'spec_name',
            'unit_price', 'quantity', 'total_price'
        ]


class OrderListSerializer(serializers.ModelSerializer):
    """订单列表序列化器"""
    item_count = serializers.ReadOnlyField()
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    
    class Meta:
        model = Order
        fields = [
            'id', 'order_no', 'status', 'status_display', 'total_amount',
            'actual_amount', 'item_count', 'created_at'
        ]


class OrderDetailSerializer(serializers.ModelSerializer):
    """订单详情序列化器"""
    items = OrderItemSerializer(many=True, read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    
    class Meta:
        model = Order
        fields = [
            'id', 'order_no', 'status', 'status_display', 'receiver_name',
            'receiver_phone', 'receiver_address', 'total_amount', 'discount_amount',
            'shipping_fee', 'actual_amount', 'remark', 'delivery_time',
            'payment_method', 'payment_time', 'shipping_company', 'tracking_number',
            'shipped_time', 'delivered_time', 'items', 'created_at', 'updated_at'
        ]


class OrderCreateSerializer(serializers.Serializer):
    """订单创建序列化器"""
    cart_ids = serializers.ListField(
        child=serializers.IntegerField(),
        help_text="购物车商品ID列表"
    )
    address_id = serializers.IntegerField(help_text="收货地址ID")
    remark = serializers.CharField(max_length=500, required=False, allow_blank=True, help_text="订单备注")
    delivery_time = serializers.CharField(max_length=100, required=False, allow_blank=True, help_text="期望送达时间")
    
    def validate_cart_ids(self, value):
        if not value:
            raise serializers.ValidationError("请选择要购买的商品")
        return value


class CartSerializer(serializers.ModelSerializer):
    """购物车序列化器"""
    flower = FlowerListSerializer(read_only=True)
    spec_name = serializers.CharField(source='flower_spec.name', read_only=True)
    spec_price = serializers.DecimalField(source='flower_spec.price', max_digits=10, decimal_places=2, read_only=True)
    total_price = serializers.ReadOnlyField()
    
    class Meta:
        model = Cart
        fields = [
            'id', 'flower', 'flower_spec', 'spec_name', 'spec_price',
            'quantity', 'total_price', 'created_at'
        ]


class CartCreateSerializer(serializers.ModelSerializer):
    """购物车创建序列化器"""
    
    class Meta:
        model = Cart
        fields = ['flower', 'flower_spec', 'quantity']
    
    def validate_quantity(self, value):
        if value <= 0:
            raise serializers.ValidationError("数量必须大于0")
        return value
    
    def validate(self, attrs):
        flower = attrs['flower']
        flower_spec = attrs.get('flower_spec')
        quantity = attrs['quantity']
        
        # 检查库存
        if flower_spec:
            if flower_spec.flower != flower:
                raise serializers.ValidationError("规格与商品不匹配")
            if flower_spec.stock < quantity:
                raise serializers.ValidationError("规格库存不足")
        else:
            if flower.stock < quantity:
                raise serializers.ValidationError("商品库存不足")
        
        return attrs


class CartUpdateSerializer(serializers.ModelSerializer):
    """购物车更新序列化器"""
    
    class Meta:
        model = Cart
        fields = ['quantity']
    
    def validate_quantity(self, value):
        if value <= 0:
            raise serializers.ValidationError("数量必须大于0")
        return value


class OrderLogSerializer(serializers.ModelSerializer):
    """订单日志序列化器"""
    
    class Meta:
        model = OrderLog
        fields = ['id', 'action', 'description', 'operator', 'created_at']


class PaymentSerializer(serializers.Serializer):
    """支付序列化器"""
    order_id = serializers.IntegerField(help_text="订单ID")
    payment_method = serializers.ChoiceField(
        choices=[('wechat', '微信支付'), ('alipay', '支付宝')],
        help_text="支付方式"
    )